package com.wiz.web.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wiz.common.RedisConstant;
import com.wiz.common.ResponseCode;
import com.wiz.data.vo.to.MabDataTO;
import com.wiz.netty.NettyXmlParseFactory;
import com.wiz.netty.message.NettyMessageFactory;
import com.wiz.netty.message.NettyMessageTO;
import com.wiz.netty.service.PoolExceptionHandler;
import com.wiz.web.dao.mapper.LoginMapper;
import com.wiz.web.manager.RedisManager;
import com.wiz.web.manager.ServiceManager;
import com.wiz.web.vo.BaseObject;
import com.wiz.web.vo.TransimissionVO;
import com.wiz.web.vo.to.ResultTO;
import com.wiz.web.vo.to.StationLoginTO;

/**
 * 基类
 * @author Hakeny
 */
public abstract class BasicServiceImpl implements ResponseCode,RedisConstant{
	
	@Resource
	private LoginMapper loginMapper;
	@Resource
	private NettyXmlParseFactory wizXmlFactory;
	@Resource
	protected ServiceManager serviceManager;
	@Resource
	protected RedisManager redisManager;
	
	//满足linux环境下需求
	protected Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	
	/**
	 * 局部中型线程池，不可滥用
	 */
	public static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
			10, 100, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5000),
			new PoolExceptionHandler());
	
	/**
	 * 线程共享数据
	 */
	public static Map<String,TransimissionVO> transMap = new HashMap<String,TransimissionVO>();
	
	
	/**
	 * 获取站点动态密钥
	 * @param stationId
	 * @return
	 */
	private String getDynamicKeyBystationId(String stationId) {
//		StationLoginTO loginTo = loginMapper.getStationLoginTO(stationId);
//		return loginTo.getDynamicKey();
		Object o = redisManager.get(String.format(STATION_DYNATIC_KEY, stationId));
		if(o == null){
			StationLoginTO loginTo = loginMapper.getStationLoginTO(stationId);
			redisManager.set(String.format(STATION_DYNATIC_KEY, stationId), loginTo.getDynamicKey());
			return loginTo.getDynamicKey();
		}else{
			return o.toString();
		}
	}
	
	/**
	 * 按照标准格式封装返回数据
	 * @param code
	 * @param msg
	 * @param o
	 * @return
	 */
	protected String returnResult(int code,String msg,BaseObject o) {
		if(o==null){
			o = new ResultTO();
		}
		o.setCode(code);
		o.setMsg(msg);
		return gson.toJson(o);
	}
	
	/**
     * 分页
     * @param cnt
     * @param pageSize
     * @return
     */
	protected Integer totalPage(int cnt,Integer pageSize){
        if(cnt==0 || pageSize==null){
            return null;
        }else if(cnt%pageSize==0){
            return cnt/pageSize;
        }else{
            return cnt/pageSize+1;
        }
    }
	
	/**
	 * 添加下发任务进定时任务队列
	 * @param stationId 站点
	 * @param idenOnly 唯一标识
	 * @param message 消息
	 * @param intervalTime 最少间隔
	 */
	protected void addTransmissionTask(final String stationId,final String idenOnly,final NettyMessageTO.MessageContent message,final long intervalTime){
//		threadPool.execute(new Thread(){
//			public void run(){
//				TransmissionTaskVO vo = new TransmissionTaskVO();
//				vo.setIdenOnly(idenOnly);
//				vo.setIntervalTime(intervalTime);
//				vo.setStartTime(System.currentTimeMillis());
//				vo.setMessage(message);
//				serviceManager.getTransmissionTaskMap().put(stationId, vo);
//			}
//		});
	}
	
	/**
	 * 获取相应的发送message信息
	 * @param mabDataTO
	 * @param messageName
	 * @param stationId
	 * @return
	 * @throws Exception
	 */
	protected NettyMessageTO.MessageContent getNettyMessage(MabDataTO mabDataTO,String messageName,String stationId) throws Exception {
		return NettyMessageFactory.getInstance().getDataMessage(mabDataTO, wizXmlFactory.getDataMessageTemplate(messageName), 
				getDynamicKeyBystationId(stationId));
	}
	
	/**
	 * 获取纯数字随机串
	 * @param length
	 * @return
	 */
	protected int getRandom(int length) {
		Random rand = new Random();
		int num = (int) Math.pow(10, length-1);
    	int i = rand.nextInt(10*num-1);
    	if(i<num){
    		i+=num;
    	}
		return i;
	}
	
	/**
	 * 验证站点是否在线
	 * @param stationId
	 * @return
	 */
	protected boolean checkStationOnline(String stationId){
		return serviceManager.getStationConnectMap().containsKey(stationId);
	}
}
